<template>
<div :class="[$style.container]">
   <el-popover
    :popper-class="$style.popper"
    ref="popper"
    placement="bottom-start"
    trigger="manual"
    v-model="visible"
    :visible-arrow="false">
    <span slot="reference"></span>
    <slot :data="data">

    </slot>
  </el-popover>
</div>
</template>

<script lang="ts">

import { Vue, Component, Provide, Watch, Ref, Prop } from 'vue-property-decorator'

@Component
export default class ContextMenu extends Vue {
  @Ref() popper!: any

  visible = false

  data: any = null

  open (e: MouseEvent, data: any) {
    e.preventDefault()
    if (this.visible) this.visible = false
    this.data = data
    this.$nextTick(() => {
      const ele = this.$el as HTMLElement
      ele.style.top = e.clientY + 'px'
      ele.style.left = e.clientX + 'px'
      this.visible = true
    })
  }

  @Provide() close () {
    this.visible = false
  }

  mounted () {
    // const menuHandler = (e: MouseEvent) => {
    //   e.preventDefault()
    //   this.open(e.clientX, e.clientY)
    // }
    const clickHandler = (e: MouseEvent) => {
      const target = e.target as HTMLElement
      const popper = this.popper?.popperElm as HTMLElement
      if (!popper || !popper.contains(target)) this.close()
    }
    // window.addEventListener('contextmenu', menuHandler)
    window.addEventListener('click', clickHandler)
    this.$once('hook:beforeDestroy', function () {
      // window.removeEventListener('contextmenu', menuHandler)
      window.removeEventListener('click', clickHandler)
    })
  }

  $style!: any
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

$col4-width: 36px;

.container {
  position: fixed;
  z-index: 9999;
}

.popper {
  padding: 0 !important;
}
</style>
